package ru.bragnikita.utils.logexplorer.logic.execution;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecuteResultHandler;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

/**
 * @author Nikita.Brazhnikov
 */
public class ScriptRunningUtils {

	private static final Logger logger = LoggerFactory.getLogger(ScriptRunningUtils.class);

	public static DefaultExecuteResultHandler runAcyncOnWindows(String scriptPath) throws ExecException {
		return runAcyncOnWindows(scriptPath, null);
	}

	public static DefaultExecuteResultHandler runAcyncOnWindows(String scriptPath, String workingDir) throws ExecException {
		final CommandLine cl = new CommandLine("cmd");
		cl.addArgument("/c");
		cl.addArgument("start");
		cl.addArgument(scriptPath);
		logger.info("Executing script command line is: {}", cl);

		final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
		DefaultExecutor executor = new DefaultExecutor();
		if (workingDir == null) {
			workingDir = new File(scriptPath).getParent();
		}
		executor.setWorkingDirectory(new File(workingDir));
		try {
			executor.execute(cl,resultHandler);
			return resultHandler;
		} catch (IOException ioe) {
			throw new ExecException(ioe);
		}
	}

	public static boolean isExecutable(String scriptFilePath) {
		if (StringUtils.isEmpty(scriptFilePath))
			return false;
		final File file = new File(scriptFilePath);
		if (file.isFile() && file.exists()) {
			final String extension = FilenameUtils.getExtension(file.getName());
			if ("bat".equals(extension) || "cmd".equals(extension))
				return true;
		}
		return false;
	}

}
